//
//  WBNetworkManger.swift
//  swiftweibo
//
//  Created by ffxk007 on 2017/6/17.
//  Copyright © 2017年 ffxk007. All rights reserved.
//

import UIKit
import AFNetworking


enum WBHTTPMethod {
    case GET
    case Post
}

/// 网络管理工具
class WBNetworkManger: AFHTTPSessionManager {
    
    /// 静态区/常量/闭包/在第一次访问时，执行闭包，并且将结果保存在shared常量中
    static let shared:WBNetworkManger = {
        
        let instance = WBNetworkManger()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    /// 访问令牌，所有网络请求，都基于此令牌(登录除外)
    ///用户登录懒加载属性
    lazy var userAccount = WBUserAccount()
    
    
    //用户登录标记[计算型属性]
    var userLogin:Bool {
        return userAccount.access_token != nil
    }
    
    
    /// 专门负责拼接token的网络请求方法
    func tokenRequest(method:WBHTTPMethod = .GET,URLString:String,parameters:[String:AnyObject]?,completion:@escaping (_ json:AnyObject?,_ isSucess:Bool)->()){
        
        
        //处理token字典
       //判断token是否为nil，为nil直接返回
        guard let token = userAccount.access_token else {
            print("没有token！需要登录")
            //发送通知，提示用户登录
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    
            completion(nil, false)
            
            return
        }
        
        //1.判断参数字典是否存在，如果为nil，应该新建一个字典
        var parameters = parameters
        
        if parameters == nil {
            parameters = [String:AnyObject]()
        }
        
        //设置参数字典//wojiushihsihishis
        parameters!["access_token"] = token as AnyObject
        
        //调用request发起真正的网络请求方法
        request(URLString: URLString, parameters: parameters!, completion: completion)
    }
    
    func request(method:WBHTTPMethod = .GET,URLString:String,parameters:[String:AnyObject],completion:@escaping (_ json:AnyObject?,_ isSucess:Bool)->()) {
       
        //成功回调
        let sucess = { (task: URLSessionDataTask, json: Any?) in
            completion((json as? [String: Any])! as AnyObject, true)

        }
        
        //失败回调
        let failure = { (task: URLSessionDataTask?, error:Error) in
          
            //针对403处理用户token过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("Token过期了")
                //发送通知,提示用户再次登录（本方法不知道被谁调用，谁接受到通知谁处理）
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "badToken")
            }
            print("网络请求 \(error)")
            completion(nil, false)
        }
        

        
        if method == .GET {
             get(URLString, parameters: parameters, progress: nil, success: sucess, failure: failure)
        }else {
            post(URLString, parameters: parameters, progress: nil, success: sucess, failure: failure)
        }
       
    }
}
